

import os
import time


from flask import Flask, send_from_directory, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from werkzeug.utils import secure_filename, redirect


from hdfs_util import read_hdfs_file, write_hdfs_file, list_hdfs_dir

from base.core import JSONEncoder
from base.response import ResMsg
# from py2neo import Graph

import logging

app = Flask(__name__)

# 连接Neo4j数据库

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:suijy3921@localhost/flask_job'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['JSON_AS_ASCII'] = False
app.config['SECRET_KEY'] = 'KJDFLSjfldskj'
# Flask 配置
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_size': 20,            # 默认10，可以适当加大
    'max_overflow': 30,         # 默认10，允许的额外连接数
    'pool_timeout': 30,         # 等待连接超时时间
    'pool_recycle': 1800        # 每30分钟自动回收连接，防止 MySQL 断开
}

# HDFS读取路由
# @app.route('/read_hdfs', methods=['GET'])
# def read_from_hdfs():
#     file_path = request.args.get('path')
#     if not file_path:
#         return jsonify({'error': 'Missing path parameter'}), 400
#
#     try:
#         content = read_hdfs_file(file_path)
#         return jsonify({'content': content})
#     except Exception as e:
#         app.logger.error(f"HDFS read error: {str(e)}")
#         return jsonify({'error': f"Failed to read file: {str(e)}"}), 500
#
#
# @app.route('/write_hdfs', methods=['POST'])
# def write_to_hdfs():
#     data = request.get_json()
#     if not data or 'path' not in data or 'content' not in data:
#         return jsonify({'error': 'Missing path or content in request'}), 400
#
#     success = write_hdfs_file(data['path'], data['content'])
#     if success:
#         return jsonify({'message': 'File written successfully'})
#     else:
#         return jsonify({'error': 'Failed to write file'}), 500
#
# @app.route('/list_hdfs', methods=['GET'])
# def list_hdfs_directory():
#     dir_path = request.args.get('path', '/')
#     try:
#         files = list_hdfs_dir(dir_path)
#         return jsonify({'path': dir_path, 'files': files})
#     except Exception as e:
#         return jsonify({'error': str(e)}), 500

UPLOAD_FOLDER="upload"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['txt','png','jpg','xls','JPG','PNG','gif','GIF'])

# 日志系统配置
handler = logging.FileHandler('error.log', encoding='UTF-8')
logging_format = logging.Formatter(
    '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
handler.setFormatter(logging_format)
app.logger.addHandler(handler)

# 返回json格式转换
app.json_encoder = JSONEncoder

db = SQLAlchemy(app)
ma = Marshmallow(app)

from api.userApi import userBp
from api.jobApi import jobBp
from api.essayApi import essayBp
from api.wordApi import wordBp

app.register_blueprint(userBp, url_prefix='/user')
app.register_blueprint(jobBp, url_prefix='/job')
app.register_blueprint(essayBp, url_prefix='/essay')
app.register_blueprint(wordBp, url_prefix='/word')

@app.route('/test')
def test():  # put application's code here
    res = ResMsg()
    test_dict = dict(name="zhang", age=19)
    res.update(data=test_dict, code=0)
    return res.data

@app.errorhandler(500)
def special_exception_handler(error):
    app.logger.error(error)
    return '请联系管理员', 500

#判断文件后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS


@app.route('/file/upload', methods=['POST'], strict_slashes=False)
def api_upload():
    res = ResMsg()
    file_dir=os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['myfile']
    if f and allowed_file(f.filename):
        fname = f.filename
        # fname = secure_filename(f.filename)
        print(fname)
        ext = fname.rsplit('.', 1)[1]
        unix_time = int(time.time())
        new_filename = str(unix_time)+'.'+ext
        f.save(os.path.join(file_dir, new_filename))
    res.update(data=new_filename, code=0)
    return res.data


@app.route('/file/download/<filename>/')
def api_download(filename):
    # print('下载..' + filename)
    return send_from_directory('upload', filename, as_attachment=False)

@app.route('/file/download/zhenti/<filename>/')
def api_zhenti(filename):
    # print('下载..' + filename)
    return send_from_directory('upload/zhenti', filename, as_attachment=False)

@app.route('/file/download/daan/<filename>/')
def api_daan(filename):
    # print('下载..' + filename)
    return send_from_directory('upload/daan', filename, as_attachment=False)

@app.before_request
def before_request():
    pass  # 可用于认证、限流等

@app.teardown_appcontext
def shutdown_session(exception=None):
    db.session.remove()

if __name__ == '__main__':
    # app.run(debug=True,host='0.0.0.0',port=5000)
    app.run()